package com.example.leoss.zhuye;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.AlertDialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.support.annotation.Nullable;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.support.v7.widget.SearchView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.leoss.Cursor1Adapter;
import com.example.leoss.Duquzifu.Data;
import com.example.leoss.Duquzifu.FileUtils;
import com.example.leoss.Duquzifu.SideBar;
import com.example.leoss.R;
import com.example.leoss.zhuye.ParseXls.Caozuo_teacher;
import com.example.leoss.zhuye.ParseXls.Teacher_info;
import com.example.leoss.zhuye.search.SearchActivity;
import com.scwang.smartrefresh.layout.api.RefreshLayout;;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import java.util.ArrayList;
import java.util.Collections;

import static com.android.volley.VolleyLog.TAG;
import static com.android.volley.VolleyLog.e;

public class SousuoFragment extends Fragment {

    public static SousuoFragment newInstance(String info) {
        Bundle args = new Bundle();
        SousuoFragment fragment = new SousuoFragment();
        args.putString("info", info);
        fragment.setArguments(args);
        return fragment;
    }

    static final String[] PROJECTION = new String[]{ContactsContract.RawContacts._ID,
            ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY};

    private ListView id_tongxun_lv1s;
    private Toolbar toolbar_a1;

    private AlertDialog alert = null;
    private AlertDialog.Builder builder = null;
    private String contact_name, contact_phone;

    private String username;
    private String address;
    private String major;
    private String phone;
    ArrayList<Data> list, mListSearch;
    Cursor1Adapter mAdapter;
    Cursor mCursor;
    Caozuo_teacher caozuo;
    View view;
    Boolean flag = true;
    private SideBar sideBar;
    private String sex = "男";
    RadioButton radioButton;
    RadioButton radioButton2;
    RadioGroup id_sousuo_add_radbt_sex1s;
    private int mFirstY;
    private int mCurrentY;
    private ObjectAnimator mAnimator;
    private int direction;
    private boolean mShow;
    private int mTouchSlop;
    private LinearLayout layou_sousuo;
    private SearchView searchView_sousuo;
    private Toolbar mToolbarContact;
    private SearchView searchView_sousuo_pe;
    private SearchView id_tongxun_search1s;
    private static boolean is = true;
    private LinearLayout linearLayout;
    FrameLayout.LayoutParams layoutParams;
    private RefreshLayout refreshLayout;

    public SousuoFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);//加上这句话，menu才会显示出来
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        //menu.clear();//这句话没用，不必加
        inflater.inflate(R.menu.toolbar, menu);
//        MenuItem menuItem=menu.findItem(R.id.search);//
//        searchView_sousuo_pe= (SearchView) MenuItemCompat.getActionView(menuItem);//加载searchview
//       //为搜索框设置监听事件
//        searchView_sousuo_pe.setSubmitButtonEnabled(false);//设置是否显示搜索按钮
//        searchView_sousuo_pe.setQueryHint("请输入联系人");
//       searchView_sousuo_pe.setIconifiedByDefault(true);//设置搜索默认为图标
//        //SearchView设置监听
//        SearchManager searchManager = (SearchManager)getActivity().getSystemService(Context.SEARCH_SERVICE);
//        searchView_sousuo_pe.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));

        super.onCreateOptionsMenu(menu, inflater);
    }


    /**
     * 判断Fragment可见与隐藏的方法
     *
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        boolean hide = hidden;

        if (hidden) {// 不在最前端界面显示

        } else {// 重新显示到最前端中
            data_show();
        }

    }

    /**
     * onResume Fragment可见，并且可以获取焦点
     */
    @Override
    public void onResume() {
        super.onResume();
        data_show();
    }

    @SuppressLint("ClickableViewAccessibility")
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        view = inflater.inflate(R.layout.fragment_sousuo, container, false);
        getActivity().getWindow().setTitle(getArguments().getString("info"));
        linearLayout = view.findViewById(R.id.sousuo_top1);
        refreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);

        mToolbarContact = view.findViewById(R.id.toolbar_sou);//meun菜单
        mToolbarContact.inflateMenu(R.menu.toolbar);  //meun_id
        // ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbarContact);

        mToolbarContact.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                //     layoutParams= new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);//定义一个LayoutParams
                int id = item.getItemId();
                //搜索
                if (id == R.id.search) {
                    startActivity(new Intent(getActivity(), SearchActivity.class));
//                    setMenuListener();
//                    Toast.makeText(getContext(),"789",Toast.LENGTH_SHORT).show();
//                    if (is){
//
//                        id_tongxun_search1s.setVisibility(View.VISIBLE);
////                        layoutParams.setMargins(0,50,0,0);//4个参数按顺序分别是左上右下
////                        linearLayout.setLayoutParams(layoutParams);
//                        is=false;
//                    }else {
//                        id_tongxun_search1s.setVisibility(View.GONE);
////                        layoutParams.setMargins(0,0,0,0);//4个参数按顺序分别是左上右下
////                        linearLayout.setLayoutParams(layoutParams);
//                        is=true;
//                    }


                }

                /*
                添加
                 */
                if (id == R.id.search1) {
                    add_user();
                }

                return true;
            }
        });


        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                data_show();
                //加载完之后结束加载
                refreshLayout.finishLoadMore();


            }
        });


        initView();
        initView1();
        data_show();


        /**
         * 隐藏Toolbar
         */
        id_tongxun_lv1s.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mFirstY = (int) event.getY();

                        break;
                    case MotionEvent.ACTION_MOVE:
                        mCurrentY = (int) event.getY();

                        if (mCurrentY > mFirstY) {//向下
                            if ((mCurrentY - mFirstY) > mTouchSlop) {
                                direction = 1;//下
                                if (!mShow) {
                                    animToolBar(direction);//显示toolBar
                                    toolbar_a1.setVisibility(View.VISIBLE);
                                    mShow = !mShow;
                                }
                            }
                        } else {
                            if ((mFirstY - mCurrentY) > mTouchSlop) {
                                direction = 0;//上
                                if (mShow) {
                                    animToolBar(direction);//隐藏toolBar
                                    //  layou_sousuo.setBottom(50);
                                    toolbar_a1.setVisibility(View.GONE);
                                    mShow = !mShow;
                                }
                            }
                        }

                        break;
                    case MotionEvent.ACTION_UP:
                        Log.d("xinwa", "Action_up");
                        break;
                }
                return false;
            }
        });

        return view;
    }


    private void initView1() {

        sideBar = (SideBar) view.findViewById(R.id.side_bar);
        sideBar.setOnStrSelectCallBack(new SideBar.ISideBarSelectCallBack() {
            @Override
            public void onSelectStr(int index, String selectStr) {
                for (int i = 0; i < list.size(); i++) {
                    if (selectStr.equalsIgnoreCase(list.get(i).getFirstLetter())) {
                        id_tongxun_lv1s.setSelection(i); // 选择到首字母出现的位置
                        return;
                    }
                }
            }
        });


    }

    /**
     * 向上滑动
     *
     * @param
     */

    private void animToolBar(int flag) {
        if (mAnimator != null && mAnimator.isRunning()) {
            mAnimator.cancel();
        }
        if (flag == 0) {//向上滑隐藏toolBar
            // mAnimator = new ObjectAnimator().ofFloat(toolbar_a1,"translationY",toolbar_a1.getTranslationY(),-toolbar_a1.getHeight());


            toolbar_a1.animate().translationY(-toolbar_a1.getHeight()).setInterpolator(new AccelerateDecelerateInterpolator());
        } else {//向下滑


            // mAnimator = new ObjectAnimator().ofFloat(toolbar_a1,"translationY",toolbar_a1.getTranslationY(),0);
            toolbar_a1.animate().translationY(0).setInterpolator(new AccelerateDecelerateInterpolator());
        }

        // mAnimator.start();
    }


    private void data_show() {

        caozuo = new Caozuo_teacher(getActivity());
        if (flag) {
            //数据库读取
            mCursor = caozuo.xianshi_all();

            list = new ArrayList<>();
            while (mCursor.moveToNext()) {
                int id = Integer.valueOf(mCursor.getString(0));//id
                String name = mCursor.getString(1);
                String sex = mCursor.getString(2);
                String address = mCursor.getString(3);
                String major = mCursor.getString(4);
                String phome = mCursor.getString(5);
                String qq = mCursor.getString(6);
                String weixing = mCursor.getString(7);
                list.add(new Data(id, name, phome, getActivity(), qq, weixing, address, major, sex, FileUtils.getFileIconByPath(sex))); // 亳[bó]属于不常见的二级汉字
            }

            Collections.sort(list);
            mAdapter = new Cursor1Adapter(list, getContext());

            if (mAdapter != null) {
                id_tongxun_lv1s.setAdapter(mAdapter);
            }

//添加一个headview，防止顶部第一条item被toolbar遮挡
//            View head = new View(getContext());
//            AbsListView.LayoutParams params = new AbsListView.LayoutParams(
//                    AbsListView.LayoutParams.MATCH_PARENT, UIUtils.dp2px(50)
//                    );
//            head.setLayoutParams(params);
//            id_tongxun_lv1s.addHeaderView(head);


        }

        mCursor.close();


        id_tongxun_lv1s.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getActivity(), String.valueOf(i), Toast.LENGTH_SHORT).show();

                TextView name = view.findViewById(R.id.id_layouttx_tv_name);
                TextView phone = view.findViewById(R.id.id_layouttx_tv_phone);
                //Imgvie点击事件
                ImageView img = view.findViewById(R.id.img_view_layout_phome);

                contact_name = name.getText().toString();//读取姓名
                contact_phone = phone.getText().toString();//读取电话号码

                confirm_call();

            }
        });


        id_tongxun_lv1s.setTextFilterEnabled(true);

//        id_tongxun_search1s.setIconifiedByDefault(false);
//        id_tongxun_search1s.setOnQueryTextListener(this);
//        id_tongxun_search1s.setSubmitButtonEnabled(false);

    }


    private void confirm_call() {
        alert = null;
        builder = new AlertDialog.Builder(getActivity());
        alert = builder.setIcon(R.drawable.img_logo)
                .setTitle("系统提示：")
                .setMessage("确定拨打" + contact_name + "的电话?")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(), "你点击了取消按钮~", Toast.LENGTH_SHORT).show();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        call_phone(contact_phone);
                        Toast.makeText(getActivity(), "你点击了确定按钮~", Toast.LENGTH_SHORT).show();
                    }
                }).create();


        alert.show();

    }

    private void call_phone(String phone_number) {
        //获取输入的电话号码
        //创建打电话的意图
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, 1);
        } else {
            Intent intent = new Intent();
            //设置拨打电话的动作
            intent.setAction(Intent.ACTION_CALL);
            //设置拨打电话的号码
            intent.setData(Uri.parse("tel:" + phone_number));
            //开启打电话的意图
            startActivity(intent);
        }
    }

    private void initView() {
        id_tongxun_lv1s = view.findViewById(R.id.id_tongxun_lv);

        // id_tongxun_search1s = view.findViewById(R.id.id_tongxun_search);

        toolbar_a1 = view.findViewById(R.id.toolbar_sou);
        // id_tongxun_search1s.setOnQueryTextListener(this);


    }

    private void add_user() {
        //实例化布局

        final View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_sousuo_addperson, null);
        //找到并对自定义布局中的控件进行操作的示例
        radioButton = view.findViewById(R.id.id_sousuo_add_radbt_man);
        radioButton2 = view.findViewById(R.id.id_sousuo_add_radbt_woman);
        id_sousuo_add_radbt_sex1s = (RadioGroup) view.findViewById(R.id.id_sousuo_add_radbt_sex);
        final EditText id_sousuo_add_ed_username1s = (EditText) view.findViewById(R.id.id_sousuo_add_ed_username);
        final EditText id_sousuo_add_ed_address1s = (EditText) view.findViewById(R.id.id_sousuo_add_ed_address);
        final EditText id_sousuo_add_ed_major1s = (EditText) view.findViewById(R.id.id_sousuo_add_ed_major);
        final EditText id_sousuo_add_ed_phone1s = view.findViewById(R.id.id_sousuo_add_ed_phone);
        //创建对话框
        AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.setIcon(R.drawable.img_logo);//设置图标
        dialog.setTitle("添加联系人");//设置标题
        dialog.setView(view);//添加布局
        //设置按键
        /**
         * RadioBution
         */
        id_sousuo_add_radbt_sex1s.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                if (radioButton.getId() == checkedId) {

                    sex = "男";
                } else if (radioButton2.getId() == checkedId) {
                    sex = "女";
                } else {
                    sex = "Bannk";
                }
            }
        });


        dialog.setButton(AlertDialog.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                username = id_sousuo_add_ed_username1s.getText().toString();
                address = id_sousuo_add_ed_address1s.getText().toString();
                major = id_sousuo_add_ed_major1s.getText().toString();
                phone = id_sousuo_add_ed_phone1s.getText().toString();


                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(phone)) {
                    Toast.makeText(getActivity(), "请输入正确的姓名和手机号！", Toast.LENGTH_SHORT).show();
                } else {
                    Caozuo_teacher caozuo_teacher = new Caozuo_teacher(getActivity());
                    Teacher_info teacher_info = new Teacher_info(username, sex, address, major, phone, "Blank", "Blank");
                    caozuo_teacher.add(teacher_info);
                    Toast.makeText(getActivity(), username + "信息添加成功！", Toast.LENGTH_SHORT).show();
                    flag = true;
                    data_show();
                }
            }


        });


        dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "容我三思", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(getActivity(), "先不加了！", Toast.LENGTH_SHORT).show();
            }
        });
        dialog.show();

    }


//    @Override
//    public boolean onQueryTextSubmit(String query) {
////        if (id_tongxun_search1s != null)
////        {
////            // 得到输入管理对象
////            InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
////            if (imm != null) {
////                // 这将让键盘在所有的情况下都被隐藏
////                imm.hideSoftInputFromWindow(id_tongxun_search1s.getWindowToken(), 0); // 输入法如果是显示状态，那么就隐藏输入法
////            }else {
////                id_tongxun_search1s.getImeOptions();
////            }
////            id_tongxun_search1s.clearFocus(); // 不获取焦点
////        }
//        return true;
//    }
//
//    @Override
//    public boolean onQueryTextChange(String s) {
////        if(s.length()!=0){
////
////            Cursor cursor = caozuo.filter_show("name like '%"+s+"%'"+"or phone like '%"+s+"%'"+"or address like '%"+s+"%'");
////            mAdapter = new Cursor1Adapter(list,getActivity());
////            id_tongxun_lv1s.setAdapter(mAdapter);
////        }else{
////
////            mCursor = caozuo.xianshi_all();
////            mAdapter = new Cursor1Adapter(list,getActivity());
////            id_tongxun_lv1s.setAdapter(mAdapter);
////        }
//
//
//        if (!TextUtils.isEmpty(s)) {
//            String text = s.toString().trim();
//            mListSearch=new ArrayList<>();
//            if (!TextUtils.isEmpty(text)) {
//
//                if (mListSearch != null && mListSearch.size() > 0) {
//                    // mListSearch 模糊搜索结果集合
//                    mListSearch.clear();
//                }
//
//                // mList 需要模糊搜索的集合
//                for (Data bean : list) {
//                    // 判断javabean中是否包含搜索字段
//                    if (bean.getName().contains(text)||bean.getPhome().contains(text)) {
//                        // 若包含，添加
//                        mListSearch.add(bean);
//                    }
//                }
//                // 给RecycleView设置搜索结果
//                mAdapter = new Cursor1Adapter(mListSearch,getActivity());
//                id_tongxun_lv1s.setAdapter(mAdapter);
//            }
//        } else {
//            // 输入框输入字段为空
//            mListSearch.clear();
//            mAdapter = new Cursor1Adapter(list,getActivity());
//            id_tongxun_lv1s.setAdapter(mAdapter);
//        }
//
//     return true;
//    }
}